import type { Directive, DirectiveBinding } from "vue";
const mouseDown = (e: MouseEvent, el: HTMLElement) => {
  // 元素的最大左边距、上边距
  const clientWidth = document.documentElement.clientWidth - el.clientWidth;
  const clientHeight = document.documentElement.clientHeight - el.clientHeight;
  // 鼠标距离边缘的距离
  const x = e.clientX - el.offsetLeft;
  const y = e.clientY - el.offsetTop;
  const move = (e: MouseEvent) => {
    const left =
      e.clientX - x < 0
        ? 0
        : e.clientX - x > clientWidth
        ? clientWidth
        : e.clientX - x;
    const top =
      e.clientY - y < 0
        ? 0
        : e.clientY - y > clientHeight
        ? clientHeight
        : e.clientY - y;
    el.style.left = left + "px";
    el.style.top = top + "px";
  };
  document.addEventListener("mousemove", move);
  document.addEventListener("mouseup", () => {
    document.removeEventListener("mousemove", move);
  });
};

export const vMove: Directive<any, void> = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    el.addEventListener("mousedown", (e) => mouseDown(e, el));
  },
  beforeUnmount(el: HTMLElement) {
    el.removeEventListener("mousedown", (e) => mouseDown(e, el));
  },
};
